package org.liveboardgames.agricola.controller;

import java.util.List;

import org.liveboardgames.agricola.domain.Change;
import org.liveboardgames.agricola.model.structure.GameSendVisitor;
import org.liveboardgames.agricola.model.structure.Visitor;

import flex.messaging.MessageBroker;
import flex.messaging.io.amf.ASObject;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.messages.Message;
import flex.messaging.services.MessageService;
import flex.messaging.services.ServiceAdapter;
import flex.messaging.util.UUIDUtils;

public class AgricolaUpdateAdapter extends ServiceAdapter {

  @Override
  public Object invoke(Message message) {
    MessageService msgService = (MessageService)getDestination().getService();

    // This is most important call which pushes,
    // the received message to all the clients.
    msgService.pushMessageToClients(message, false);

    return null;
  }

  @SuppressWarnings("unchecked")
  public void publishGameUpdates(Long gameId, List<Change> changes) {
    if (changes != null) {
      Visitor visitor = new GameSendVisitor();
      for (Change change : changes) {
        change.acceptVisit(visitor);
      }
    }
    
    AsyncMessage message = new AsyncMessage();
    message.setDestination("agricolaUpdate");
    message.setHeader("gameId", gameId);
    message.setMessageId(UUIDUtils.createUUID());
    ASObject body = new ASObject();
    body.put("changes", changes);
    message.setBody(body);

    MessageBroker messageBroker = MessageBroker.getMessageBroker(null);
    messageBroker.routeMessageToService(message, null);
  }
}
